package com.htd.htdapmservice.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.acooly.core.utils.Ids;
import com.alibaba.fastjson.JSON;
import com.htd.htdapmapi.alarm.request.AlarmInto;
import com.htd.htdapmapi.alarm.result.AlarmResult;
import com.htd.htdapmcommon.constants.AlarmConstants;
import com.htd.htdapmcommon.constants.ErrorCodeConstants;
import com.htd.htdapmcommon.util.HttpUtils;
import com.htd.htdapmcommon.util.RedisUtil;
import com.htd.htdapmcommon.util.StringUtil;
import com.htd.htdapmdmo.AlarmsInfo;
import com.htd.htdapmdmo.OneAlertKey;
import com.htd.htdapmservice.dao.AlarmsInfoDao;
import com.htd.htdapmservice.result.CreateAlarmResult;
import com.htd.htdapmservice.service.intf.AlarmsInfoService;
import com.htd.htdapmservice.service.intf.OneAlertKeyService;

@Service
public class AlarmsInfoServiceImpl implements AlarmsInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AlarmsInfoServiceImpl.class);
    @Autowired
    private AlarmsInfoDao alarmsInfoDao;

    @Autowired
    private OneAlertKeyService oneAlertKeyService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 调用接口--创建告警API
     */
    @Value("${app.getCreateAlarmPath}")
    private String getCreateAlarmPath;


    @Override
    public List<AlarmsInfo> getAlarmsInfoListBySendStatus(String sendStatus) {
        return alarmsInfoDao.getAlarmsInfoListBySendStatus(sendStatus);
    }

    @Override
    public AlarmResult createAlarm(AlarmInto alarmInto) {
        AlarmResult alarmResult = null;
        //参数校验
        try{
            if(!checkCreateAlarm(alarmInto)){
                alarmResult =new AlarmResult();
                alarmResult.setResponseMsg(ErrorCodeConstants.ERROR_PARAM_MSG);
                alarmResult.setResponseCode(ErrorCodeConstants.ERROR_PARAM_CODE);
                return alarmResult;
            }
            CreateAlarmResult createAlarmResult  =sendAlarmInfo(alarmInto);
            alarmResult =new AlarmResult();
            if(null== createAlarmResult){
                alarmResult.fail(ErrorCodeConstants.SYSTEM_ERROR_CODE,ErrorCodeConstants.SYSTEM_ERROR_MSG);
                return alarmResult;
            }
            if(!AlarmConstants.ALARMA_SUCCESS.equals(createAlarmResult.getCode())){
                alarmResult.fail(createAlarmResult.getCode(),createAlarmResult.getMessage());
                return alarmResult;
            }
            return alarmResult;
        }catch (Exception e){
            LOGGER.error("调用第三方告警接口异常",e);
            alarmResult =new AlarmResult();
            alarmResult.setResponseMsg(ErrorCodeConstants.SYSTEM_ERROR_MSG);
            alarmResult.setResponseCode(ErrorCodeConstants.SYSTEM_ERROR_CODE);
            return alarmResult;
        }
    }

    @Override
    public int updateSendStatusByAlarmsId(Map<String, Object> paramMap) {
        return alarmsInfoDao.updateSendStatusByAlarmsId(paramMap);
    }

    /**
     * 校验创建告警接口参数
     * @param alarmInto
     * @return true/false
     */
    private boolean checkCreateAlarm(AlarmInto alarmInto){
        if(StringUtil.isAnyNullOrEmpty(alarmInto.getAlarmsDetail(),alarmInto.getEventType(),alarmInto.getProductType())){
            LOGGER.info("参数校验不通过");
            return false;
        }
        return true;
    }

    /**
     * 发送告警服务到第三方告警中心平台
     * @param alarmInto
     * @return
     */
    public CreateAlarmResult sendAlarmInfo(AlarmInto alarmInto){
        HashMap<String, String> params = new HashMap<String, String>();
        if (!redisUtil.exists(AlarmConstants.getOneAlertKey(alarmInto.getProductType()))){
            OneAlertKey oneAlertKey = oneAlertKeyService.findOneAlertKeyByProductCode(alarmInto.getProductType());
            redisUtil.set(AlarmConstants.getOneAlertKey(alarmInto.getProductType()),oneAlertKey.getProductKeyt(),AlarmConstants.ONE_ALERT_TOKEN_EXPIRE);
            params.put("app", oneAlertKey.getProductKeyt());
        }else {
            params.put("app", redisUtil.get(AlarmConstants.getOneAlertKey(alarmInto.getProductType())));
        }
        params.put("eventType", alarmInto.getEventType());
        params.put("eventId", Ids.getDid());
        params.put("alarmContent",alarmInto.getAlarmsDetail());

        if (StringUtils.isNotBlank(alarmInto.getAlarmsTitle())) {
            params.put("entityName",alarmInto.getAlarmsTitle());
        }
        if (StringUtils.isNotBlank(alarmInto.getPriority())) {
            params.put("priority",alarmInto.getPriority());
        }
        if (StringUtils.isNotBlank(alarmInto.getHost())) {
            params.put("host",alarmInto.getHost());
        }
        if (StringUtils.isNotBlank(alarmInto.getService())) {
            params.put("service",alarmInto.getService());
        }
        LOGGER.info("告警params:{}",params);
        String result = HttpUtils.sendPostMessage(params, AlarmConstants.ENCODE_UTF, getCreateAlarmPath);
        CreateAlarmResult createAlarmResult = JSON.parseObject(result,CreateAlarmResult.class);
        return createAlarmResult;
    }

}
